/**
 * Gerenciador de Projetos de Layout
 *
 * @this {LayoutProject}
 * @version
 */

function LayoutProject() {

    /**
     * Variaveis
     */
    var _projectIsOpened = false;
    var _timer = null;
    var _oClassOwner = this;

    /**
     * Inicializa o objeto da classe
     */
    this.init = function() {

        _oClassOwner.autoSave(document.getElementById('autosave').checked, document.getElementById('autosaveinterval').value);
    }

    /**
     * Funcoes
     */
    this.openProject = function() {

        YAHOO.util.Connect.setForm('openprojectform', true);
        var uploadHandler = {
            upload: function(o) {

                // Processa os dados em formato JSON retornados pelo servidor
                try {
                    var JSONData = YAHOO.lang.JSON.parse(o.responseText);
                    alert(EAppInfoMessages.eProjectOpened);
                    _oClassOwner.loadProject(JSONData);
                }
                catch (exception) {
                    alert(EAppInfoMessages.eOpenProjectFailed + o.responseText);
                }
                //_oOpenProjectDialog.hide();
                var oUIOpenProjectDialog = UIInstance.getUIOpenProjectDialogInstance();
                oUIOpenProjectDialog.hideOpenProjectDialog();
            }
        };
        YAHOO.util.Connect.asyncRequest('POST', 'index.php/clayoutproject/doOpen', uploadHandler);
    }

    this.createProject = function() {

        YAHOO.util.Connect.setForm('createprojectform', false);
        var response = {

            success: function(o) {

                // Processa os dados em formato JSON retornados pelo servidor
                try {
                    var JSONData = YAHOO.lang.JSON.parse(o.responseText);
                    alert(EAppInfoMessages.eProjectCreated);
                    _oClassOwner.loadProject(JSONData);
                    var oUICreateProjectDialog = UIInstance.getUICreateProjectDialogInstance();
                    oUICreateProjectDialog.hideCreateProjectDialog();
                }
                catch (exception) {
                    alert(EAppInfoMessages.eCreateProjectFailed + o.responseText);
                }
            },

            failure: function(o) {
                alert(EAppInfoMessages.eCommunicationServerFailed);
            }

        };
        YAHOO.util.Connect.asyncRequest('POST', 'index.php/clayoutproject/doCreate', response);
    }

    this.saveProject = function(bGetFile) {

        //gera uma string no formato json, para transferir os dados ao servidor
        var projectContent = ModelInstance.getLayoutComposer().getProjectContent();
        var JSONData = YAHOO.lang.JSON.stringify(projectContent);

        YAHOO.util.Connect.setDefaultPostHeader(false);
        YAHOO.util.Connect.initHeader("Content-type", "application/x-www-form-urlencoded");
        var response = {

            success: function(o) {
                var clock = new Clock();
                document.getElementById("autosavestatus").innerHTML = EAppInfoMessages.eProjectSavedAt + clock.getDateTime();
                if(bGetFile) {
                    //obtem o arquivo de projeto salvo, via download
                    var projectName = projectContent.name;
                    document.getElementById('saveasprojectform').projectname.value = projectName;
                    document.getElementById('saveasprojectform').submit();
                }
            },

            failure: function(o) {
                alert(EAppInfoMessages.eCommunicationServerFailed);
            }

        };
        YAHOO.util.Connect.asyncRequest("POST", "index.php/clayoutproject/doSave", response, "data="+JSONData);
    }

    this.saveAsProject = function() {
        _oClassOwner.saveProject(true);
    }

    this.printLayout = function() {

        var oUIMapLayoutArea = UIInstance.getUIMapLayoutAreaInstance();
        var SVGData = oUIMapLayoutArea.extractSVGContent();

        //recupera a extensao escolhida
        var extensions = document.getElementById('printlayoutform').extensions;
        var htmlOptionExt = extensions.options[extensions.selectedIndex].value;

        YAHOO.util.Connect.setDefaultPostHeader(false);
        YAHOO.util.Connect.initHeader("Content-type", "application/x-www-form-urlencoded");
        var response = {

            success: function(o) {

                switch(o.responseText) {

                    case EGeneralTypes.eNoneExeConvert:
                        alert(EAppInfoMessages.eGenerateMapLayoutFailed + EAppInfoMessages.eConvertUnavailable);
                        break;
                    case "":
                        alert(EAppInfoMessages.eGenerateMapLayoutFailed + EAppInfoMessages.ePrintLayoutRoutineFailed);
                        break;
                    default:
                        document.getElementById('getlayoutfileform').filename.value = o.responseText;
                        document.getElementById('getlayoutfileform').submit();
                }
            },

            failure: function(o) {
                alert(EAppInfoMessages.eCommunicationServerFailed);
            }

        };
        YAHOO.util.Connect.asyncRequest("POST", "index.php/clayoutproject/doPrint", response, "data="+SVGData+"&extensions="+htmlOptionExt);
    }

    this.autoSave = function(bOption, interval) {
        if(bOption) {
            if(_oClassOwner.projectIsOpened()) {
                _oClassOwner.saveProject(false);
            }
            //habilita gravacao automatica do projeto
            _timer = setTimeout(_oClassOwner.autoSave, (interval*60*1000), bOption, interval);

        } else {
            //desabilita gravacao automatica do projeto
            clearTimeout(_timer);
        }
    }

    this.projectIsOpened = function() {
        return _projectIsOpened;
    }

    this.setProjectIsOpened = function(bProjectIsOpened) {
        _projectIsOpened = bProjectIsOpened;
    }

    /**
     * Carrega (abre) o projeto na aplicacao
     */
    this.loadProject = function(JSONData) {

        //o projeto esta em edicao
        _oClassOwner.setProjectIsOpened(true);

        //"encaminha" o conteudo do projeto para o compositor de layout
        ModelInstance.getLayoutComposer().loadCompositionEnvironment(JSONData);
    }

    /**
     * Fecha o projeto
     */
    this.closeProject = function() {

        //"avisa" o compositor de layout que o projeto esta finalizado
        ModelInstance.getLayoutComposer().unloadCompositionEnvironment();

        //o projeto nao esta em edicao
        _oClassOwner.setProjectIsOpened(false);
    }

    /**
     * Chamada do inicializador da classe
     */
    this.init();
}

